#include "ShotCutCaption.h"
#include <QFontDatabase>

ShotCutCaption::ShotCutCaption(const JsonShotCutCaption& JsonData)
{
    for(JsonShotCutCaption::CaptionInfo* VideoInfo : JsonData.JsonCaptionInfoArray)
    {
        CaptionArray.push_back(make_pair(shared_ptr<JsonShotCutCaption::CaptionInfo>(VideoInfo), make_shared<Caption>()));
    }
    
    SetProPerty();
}

void ShotCutCaption::SetProPerty()
{
    std::shared_ptr<GlobalData> Global = GlobalData::GetGlobalData();
    float SrcVideoWidth = Global->GetVideoWidth(), SrcVideoHeight = Global->GetVideoHeight();
    for(auto CaptionItem : CaptionArray)
    {
        QString FontFamily = "";
        int FontID = -1;
        double TimeSpeed = CaptionItem.first->ZoomRate;
        float StartTime = CaptionItem.first->BeginTime;
        float EndTime = CaptionItem.first->EndTime;
        double Frames = TimeSpeed * (EndTime - StartTime) * Global->GetFps();
        double CaptionTop = CaptionItem.first->CoordY / SrcVideoHeight;
            
        std::string CaptionString = CaptionItem.first->Text;
        std::replace(CaptionString.begin(), CaptionString.end(), ',', '\n'); //切割字符串
        
        if(!CaptionItem.first->FontFile.empty())
        {
            FontID = QFontDatabase::addApplicationFont(QString::fromStdString(CaptionItem.first->FontFile));
            if(FontID != -1)
            {
                FontFamily = QFontDatabase::applicationFontFamilies(FontID).at(0);
            }
            else
            {
                std::cout << "Filed to load: " << CaptionItem.first->FontFile << std::endl;
            }
        }
        
        CaptionItem.second->Layer(CaptionItem.first->Layer);
        CaptionItem.second->Position(CaptionItem.first->PositionTime);
        CaptionItem.second->Start(TimeSpeed * StartTime);
        CaptionItem.second->End(TimeSpeed * EndTime);
        CaptionItem.second->CaptionText("00:00:00:000 --> 01:00:00:000\n" + CaptionString);
        CaptionItem.second->color = Color(CaptionItem.first->Color);
        CaptionItem.second->stroke = Color(CaptionItem.first->StrokeColor);
        CaptionItem.second->stroke_width = CaptionItem.first->StrokeWidth;
        CaptionItem.second->font_size = CaptionItem.first->FontSize;
        if(!FontFamily.toStdString().empty())
        {
            CaptionItem.second->font_name = FontFamily.toStdString();
        }
        else
        {
            CaptionItem.second->font_name = CaptionItem.first->FontType;
        }
        CaptionItem.second->left = CaptionItem.first->CoordX / SrcVideoWidth - 0.5f;
        CaptionItem.second->top = CaptionTop;
        CaptionItem.second->top.AddPoint(0, CaptionTop, LINEAR);
        CaptionItem.second->top.AddPoint(Frames, CaptionTop - CaptionItem.first->Rate, LINEAR);
        CaptionItem.second->font_alpha = CaptionItem.first->Alpha;
    }
}
